package com.ruoyi.sales.controller;

import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.core.domain.entity.ZcStock;
import com.ruoyi.common.exception.UtilException;
import com.ruoyi.sales.domain.ZcProduct;
import com.ruoyi.sales.domain.ZcSalesList;
import com.ruoyi.sales.domain.ZcStoreMaterial;
import com.ruoyi.sales.service.*;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.sales.domain.ZcSalesProducts;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

import static org.springframework.transaction.annotation.Propagation.MANDATORY;

/**
 * 销售产品Controller
 * 
 * @author woo
 * @date 2024-04-09
 */
@RestController
@RequestMapping("/sales/salesProducts")
public class ZcSalesProductsController extends BaseController
{
    @Autowired
    private IZcSalesProductsService zcSalesProductsService;
    @Autowired
    private IZcProductService productService;
    @Autowired
    private IZcSalesListService salesListService;
    @Autowired
    private IZcStoreMaterialService zcStoreMaterialService;
    @Autowired
    private IZcStockService stockService;

    /**
     * 查询销售产品列表
     */
    @PreAuthorize("@ss.hasPermi('sales:salesProducts:list')")
    @GetMapping("/list")
    public TableDataInfo list(ZcSalesProducts zcSalesProducts,Long salesId)
    {
        startPage();
        List<ZcSalesProducts> list = zcSalesProductsService.selectZcSalesProductsList(zcSalesProducts,salesId);
        return getDataTable(list);
    }

    /**
     * 导出销售产品列表
     */
//    @PreAuthorize("@ss.hasPermi('sales:salesProducts:export')")
//    @Log(title = "销售产品", businessType = BusinessType.EXPORT)
//    @PostMapping("/export")
//    public void export(HttpServletResponse response, ZcSalesProducts zcSalesProducts)
//    {
//        List<ZcSalesProducts> list = zcSalesProductsService.selectZcSalesProductsList(zcSalesProducts);
//        ExcelUtil<ZcSalesProducts> util = new ExcelUtil<ZcSalesProducts>(ZcSalesProducts.class);
//        util.exportExcel(response, list, "销售产品数据");
//    }

    /**
     * 获取销售产品详细信息
     */
    @PreAuthorize("@ss.hasPermi('sales:salesProducts:query')")
    @GetMapping(value = "/{productId}")
    public AjaxResult getInfo(@PathVariable("productId") Long productId)
    {
        return success(zcSalesProductsService.selectZcSalesProductsByProductId(productId));
    }

    /**
     * 新增销售产品
     */
    @PreAuthorize("@ss.hasPermi('sales:salesProducts:add')")
    @Log(title = "销售产品", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ZcSalesProducts zcSalesProducts)
    {
        List<ZcSalesProducts> productsList = zcSalesProductsService.selectAll();
        for (ZcSalesProducts products : productsList) {
            if (products.getSalesId().equals(zcSalesProducts.getSalesId()) && products.getProductNumber().equals(zcSalesProducts.getProductNumber())){
                return AjaxResult.error("已有该产品，新增失败，请重新核对");
            }
        }
        return toAjax(zcSalesProductsService.insertZcSalesProducts(zcSalesProducts));
    }

    /**
     * 修改销售产品
     */
    @PreAuthorize("@ss.hasPermi('sales:salesProducts:edit')")
    @Log(title = "销售产品", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ZcSalesProducts zcSalesProducts)
    {
//        List<ZcSalesProducts> productsList = zcSalesProductsService.selectAll();
//        for (ZcSalesProducts products : productsList) {
//            if (products.getSalesId().equals(zcSalesProducts.getSalesId()) && products.getProductNumber().equals(zcSalesProducts.getProductNumber())){
//                return AjaxResult.error("已有该产品，修改失败，请重新核对");
//            }
//        }
        return toAjax(zcSalesProductsService.updateZcSalesProducts(zcSalesProducts));
    }

    /**
     * 删除销售产品
     */
    @PreAuthorize("@ss.hasPermi('sales:salesProducts:remove')")
    @Log(title = "销售产品", businessType = BusinessType.DELETE)
	@DeleteMapping("/{productIds}")
    public AjaxResult remove(@PathVariable Long[] productIds)
    {
        return toAjax(zcSalesProductsService.deleteZcSalesProductsByProductIds(productIds));
    }

    /**
     * 获取产品列表
     */
    @PreAuthorize("@ss.hasPermi('sales:salesProducts:list')")
    @GetMapping("/productsList")
    public AjaxResult productsList(){
        List<ZcProduct> productList = productService.selectAllProducts();
        return success(productList);
    }

    /**
     * 生成生产计划提交接口
     */
    @PostMapping("/productPlan")
    @Transactional
    public AjaxResult productPlan (@RequestBody ZcSalesProducts zcSalesProducts){
        // 检查成品仓库是否有对应产品，有则减去成品仓库数量并放入中转字段，返回剩余需要生产米数
        Long lastCount = zcSalesProductsService.checkStoreProducts(zcSalesProducts);
        if (lastCount>0){
            Long productNumber = zcSalesProducts.getProductNumber();
            ZcProduct zcProduct = productService.selectZcProductByProductId(productNumber);
            ZcStock zcStock = stockService.selectStockById(zcProduct.getStockId());
            Long lastMaterial = zcStoreMaterialService.checkStoreMaterial(productNumber,lastCount);
            if (lastMaterial>0){

                throw new UtilException("原料不足，请通知办事处至少购入"+lastMaterial+"数量的"+zcStock.getStockName());
//                return AjaxResult.error("原料不足，请通知办事处");
            }else if (lastMaterial==0){
                zcSalesProducts.setStatus("1");
            }
        }else if (lastCount == 0){
            zcSalesProducts.setStatus("2");
        }
        zcSalesProductsService.updateZcSalesProducts(zcSalesProducts);
        return success();
    }



}
